package com.changpay.zywy.ui.activity.main

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Process
import android.support.design.widget.Snackbar
import android.support.design.widget.TabLayout
import android.support.v4.app.FragmentTransaction
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.changpay.zywy.BuildConfig
import com.changpay.zywy.R
import com.changpay.zywy.app.App
import com.changpay.zywy.base.BaseMvpActivity
import com.changpay.zywy.ext.showToast
import com.changpay.zywy.ext.sss
import com.changpay.zywy.http.RetrofitHelper
import com.changpay.zywy.mvp.contract.MainContract
import com.changpay.zywy.mvp.presenter.MainPresenter
import com.changpay.zywy.ui.activity.login.LoginActivity
import com.changpay.zywy.ui.fragment.main.*
import com.changpay.zywy.utils.DoubleClickExit
import kale.ui.view.dialog.EasyDialog
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : BaseMvpActivity<MainContract.View, MainContract.Presenter>(), MainContract.View {


    private val BOTTOM_INDEX: String = "bottom_index"

    private val FRAGMENT_HOME = 0x01
    private val FRAGMENT_COUNT = 0x02
    private val FRAGMENT_QRCODE = 0x03
    private val FRAGMENT_INFO = 0x04
    private val FRAGMENT_MINE = 0x05

    private var mIndex = FRAGMENT_HOME

    private var mHomeFragment: HomeFragment? = null
    private var mCountFragment: CountTypeFragment? = null
    private var mQRFragment: QRFragment? = null
    private var mShopFragment: ShopFragment? = null
    private var mMineFragment: MineFragment? = null

    override fun useEventBus(): Boolean = false

    var tabNames: Array<String>? = null
    var tabIcons: IntArray? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        if (savedInstanceState != null) {
            mIndex = savedInstanceState.getInt(BOTTOM_INDEX)
        }
        super.onCreate(savedInstanceState)
    }

    override fun createPresenter(): MainContract.Presenter = MainPresenter()

    override fun attachLayoutRes(): Int = R.layout.activity_main

    override fun initView() {
        super.initView()

        initMenus()
        tab_layout.addTab(tab_layout.newTab())
        tab_layout.addTab(tab_layout.newTab())
        tab_layout.addTab(tab_layout.newTab())
        tab_layout.addTab(tab_layout.newTab())
        for (i in tabNames?.indices!!) {
            tab_layout.getTabAt(i)!!.customView = getTabView(tabNames!![i], tabIcons!![i])
        }

        // 设置监听
        tab_layout.setOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {

                //选中了tab的逻辑
                //                showToast(tab.getPosition()+""
                when (tab.position) {
                    0 -> {
                        showFragment(FRAGMENT_HOME)

                    }
                    1 -> {
                        showFragment(FRAGMENT_COUNT)

                    }
                    2 -> {
                        showFragment(FRAGMENT_QRCODE)

                    }
                    3 -> {
                        showFragment(FRAGMENT_MINE)

                    }
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                //未选中tab的逻辑
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                //再次选中tab的逻辑
                //                showToast(tab.getPosition()+"");
            }
        })


        showFragment(mIndex)
    }

    override fun start() {
        checkVersion()
        
        RetrofitHelper.service.getUserInfo(token).sss(this)
        {
        }
    }

    override fun initData() {

    }

    override fun showDefaultMsg(msg: String) {
        if (msg == "请登录") {
            val builder = EasyDialog.builder(this) // 建立builder对象
            builder.setTitle("提示")
                .setMessage("您的登录凭证已失效，请重新登录！")
                // 设置下方的三个按钮
                .setPositiveButton("确定") { _: DialogInterface, _: Int ->
                    Intent(this@MainActivity, LoginActivity::class.java).run {
                        token = ""
                        startActivity(this)
                    }
                }
                .setCancelable(false) // 点击空白处可以关闭
            builder.build<EasyDialog>().show(supportFragmentManager, "")
        } else {
            showToast(msg)
        }
    }

    /**
     * 隐藏所有的Fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
        mHomeFragment?.let { transaction.hide(it) }
        mCountFragment?.let { transaction.hide(it) }
        mQRFragment?.let { transaction.hide(it) }
        mShopFragment?.let { transaction.hide(it) }
        mMineFragment?.let { transaction.hide(it) }
    }


    /**
     * 展示Fragment
     * @param index
     */
    private fun showFragment(index: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)
        mIndex = index
        when (index) {
            FRAGMENT_HOME // 首页
            -> {
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance()
                    transaction.add(R.id.container, mHomeFragment!!, "home")
                } else {
                    transaction.show(mHomeFragment!!)
                }
            }
            FRAGMENT_COUNT // 统计
            -> {
                if (mCountFragment == null) {
                    mCountFragment = CountTypeFragment.getInstance()
                    transaction.add(R.id.container, mCountFragment!!, "count")
                } else {
                    transaction.show(mCountFragment!!)
                }
            }
            FRAGMENT_QRCODE // 二维码
            -> {
                if (mQRFragment == null) {
                    mQRFragment = QRFragment.getInstance()
                    transaction.add(R.id.container, mQRFragment!!, "qrCode")
                } else {
                    transaction.show(mQRFragment!!)
                }
            }
            FRAGMENT_INFO // 商店
            -> {
                if (mShopFragment == null) {
                    mShopFragment = ShopFragment.getInstance()
                    transaction.add(R.id.container, mShopFragment!!, "shop")
                } else {
                    transaction.show(mShopFragment!!)
                }
            }
            FRAGMENT_MINE // 公众号
            -> {
                if (mMineFragment == null) {
                    mMineFragment = MineFragment.getInstance()
                    transaction.add(R.id.container, mMineFragment!!, "mine")
                } else {
                    transaction.show(mMineFragment!!)
                }
            }
        }
        transaction.commit()
    }


    override fun onDestroy() {
        super.onDestroy()
        mHomeFragment = null
        mCountFragment = null
        mQRFragment = null
        mShopFragment = null
        mMineFragment = null
    }


    override fun onBackPressed() {
        if (!DoubleClickExit.check()) {
            Snackbar.make(
                this.window.decorView.findViewById(android.R.id.content),
                "再按一次退出 App!",
                Snackbar.LENGTH_SHORT
            ).show()
        } else {
            super.onBackPressed()
            val app = App.instance as App
            app.finishAllActivity()
            Handler().postDelayed({
                Process.killProcess(Process.myPid())
                System.exit(0)
                System.gc()
            }, 500)
        }
    }

    private fun checkVersion() {
        val versionName = BuildConfig.VERSION_NAME
        val params = HashMap<String, String>()
        RetrofitHelper.service.get_app_version_info(params).sss(this) {
            val versionBean = it.result
            val versionNumer =   versionBean.version.toDouble()  // 线上
            val versionNameNumer =   versionName.toDouble()  // 本地
            if (versionNumer > versionNameNumer) {
                val instance = AllenVersionChecker.getInstance()
                val downloadBuilder = instance.downloadOnly(
                    UIData.create().setDownloadUrl(versionBean.download_url).setTitle(versionBean.title).setContent(
                        versionBean.context
                    )
                )
                if (versionBean.isForce()) {
                    downloadBuilder.setForceUpdateListener {
                        (App.instance as App).finishAllActivity()
                        Handler().postDelayed({
                            Process.killProcess(Process.myPid())
                            System.exit(0)
                            System.gc()
                        }, 500)
                    }
                }
                downloadBuilder.setForceRedownload(true).executeMission(this)
            }
        }
    }

    private fun initMenus() {
        tabNames = resources.getStringArray(R.array.main_tabs)
        val ar = resources.obtainTypedArray(R.array.main_tab_icons)
        val len = ar.length()
        tabIcons = IntArray(len)
        for (i in 0 until len) {
            tabIcons!![i] = ar.getResourceId(i, 0)
        }
        ar.recycle()
    }

    private fun getTabView(tabName: String, tabIcon: Int): View {
        val view = LayoutInflater.from(this).inflate(R.layout.tab_layout, null)
        val iv_tab: ImageView = view.findViewById(R.id.iv_tab)
        val tv_tab: TextView = view.findViewById(R.id.tv_tab)
        iv_tab.setImageResource(tabIcon)
        tv_tab.text = tabName
        return view
    }

}


